package com.sifang.sfuserservice.queue;

import com.sifang.sfuserservice.dto.UserDto;
import com.sifang.sfuserservice.entity.UserEntity;
import com.sifang.sfuserservice.service.UserService;
import com.sifang.sfuserservice.utils.SnowflakeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

@Service
public class DataDispatch {

    private static final Integer MAX_QUEUE_SIZE = 100000;
    private static final Integer BATCH_HANDLE_COUNT = 1000;
    public static final BlockingQueue<UserDto> USER_QUEUE = new LinkedBlockingQueue(MAX_QUEUE_SIZE);
    @Autowired
    private UserService userService;

    @PostConstruct
    public void init() {
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(20);
        scheduledExecutorService.scheduleAtFixedRate(() -> {

            int size = USER_QUEUE.size();
            //System.out.println("队列当前数据量:{}" + size);
            //如果队列没数据,表示这段时间没有请求,直接返回
            if (size == 0) {
                return;
            }

            List<UserEntity> list = new ArrayList<>();
            //System.out.println("合并请求数:" + size);

            // 分批处理 一次100条
            for (int i = 0; i < BATCH_HANDLE_COUNT; i++) {
                UserDto poll = USER_QUEUE.poll();
                if (poll == null) {
                    break;
                }
                UserEntity userEntity = UserEntity.builder().id(SnowflakeUtil.snowflakeId()).name(poll.getName()).registerTime(poll.getRegisterTime()).build();
                list.add(userEntity);
            }


            if (CollectionUtils.isEmpty(list)) {
                return;
            }
            // 批量保存数据
            userService.saveBatch(list);

        }, 0, 100, TimeUnit.MILLISECONDS);
    }
}
